import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { Users } from '../../entities/Users.entity'
import { Child } from '../../entities/Child.entity'
import { UserChild } from '../../entities/UserChild.entity'

@Provide()
export class UserChildService {
  @InjectEntityModel(Users)
  userRepo!: Repository<Users>

  @InjectEntityModel(Child)
  childRepo!: Repository<Child>

  @InjectEntityModel(UserChild)
  userChildRepo!: Repository<UserChild>

  // 根据用户ID获取关联的儿童信息
  async getChildrenByUserId(userId: string) {
    // 查询指定用户
    const user = await this.userRepo.findOne({ where: { id: userId } })
    if (!user) {
      throw new Error('用户不存在')
    }

    // 通过 UserChild 关联表查询该用户关联的所有儿童ID
    const userChildRelations = await this.userChildRepo.find({
      where: { userId }
    })

    if (userChildRelations.length === 0) {
      throw new Error('未找到关联的儿童')
    }

    // 提取儿童ID列表
    const childIds = userChildRelations.map(relation => relation.childId)

    // 查询关联的儿童详情
    const children = await this.childRepo
      .createQueryBuilder('child')
      .where('child.id IN (:...childIds)', { childIds })
      .andWhere('child.is_disabled = :isDisabled', { isDisabled: 0 })
      .getMany()

    return {
      items: children,
      total: children.length
    }
  }

  // 添加用户儿童关联
  async addUserChildRelation(data: {
    userId: string
    childId: number
    relationType?: number
  }) {
    // 检查是否已存在关联
    const existingRelation = await this.userChildRepo.findOne({
      where: { userId: data.userId, childId: data.childId }
    })

    if (existingRelation) {
      throw new Error('该用户已关联此儿童')
    }

    // 创建新的关联
    const userChild = this.userChildRepo.create({
      userId: data.userId,
      childId: data.childId,
      relationType: data.relationType || 3 // 默认为监护人
    })

    return await this.userChildRepo.save(userChild)
  }

  // 删除用户儿童关联
  async removeUserChildRelation(userId: string, childId: number) {
    const relation = await this.userChildRepo.findOne({
      where: { userId, childId }
    })

    if (!relation) {
      throw new Error('关联关系不存在')
    }

    await this.userChildRepo.remove(relation)
    return true
  }

  // 创建新儿童
  async createChild(data: {
    name: string
    phone: string
    homeAddress?: string
    birthday?: string
    headImg?: string
    guardian?: string
    gender?: number
    userId?: string
  }) {
    // 验证必填字段
    if (!data.name || data.name.trim().length === 0) {
      throw new Error('姓名不能为空')
    }
    if (data.name.length > 255) {
      throw new Error('姓名长度不能超过255个字符')
    }

    if (!data.phone || data.phone.trim().length === 0) {
      throw new Error('电话不能为空')
    }
    if (data.phone.length > 20) {
      throw new Error('电话长度不能超过20个字符')
    }

    // 验证可选字段
    if (data.homeAddress && data.homeAddress.length > 255) {
      throw new Error('家庭地址长度不能超过255个字符')
    }

    if (data.birthday) {
      const dateRegex = /^\d{4}-\d{2}-\d{2}$/
      if (!dateRegex.test(data.birthday)) {
        throw new Error('生日格式不正确，应为YYYY-MM-DD')
      }
    }

    if (data.headImg && data.headImg.length > 255) {
      throw new Error('头像URL长度不能超过255个字符')
    }

    if (data.guardian && data.guardian.length > 255) {
      throw new Error('监护人长度不能超过255个字符')
    }

    if (data.gender !== undefined) {
      if (data.gender !== 1 && data.gender !== 2) {
        throw new Error('性别值必须为1（男）或2（女）')
      }
    }

    // 创建新儿童
    const child = this.childRepo.create({
      name: data.name,
      phone: data.phone,
      homeAddress: data.homeAddress || null,
      birthday: data.birthday || null,
      headImg: data.headImg || null,
      guardian: data.guardian || null,
      gender: data.gender !== undefined ? (data.gender === 1) : null,
      isDisabled: false
    })

    const childAns =  await this.childRepo.save(child)

    // 如果传入了userId，自动创建用户-儿童关联
    if (data.userId) {
      const user = await this.userRepo.findOne({ where: { id: data.userId } })
      if (!user) {
        throw new Error('用户不存在')
      }

      // 检查是否已存在关联
      const existingRelation = await this.userChildRepo.findOne({
        where: { userId: data.userId, childId: childAns.id }
      })

      if (!existingRelation) {
        // 创建用户-儿童关联记录
        const userChild = this.userChildRepo.create({
          userId: data.userId,
          childId: childAns.id,
          relationType: 3 // 默认为监护人
        })
        await this.userChildRepo.save(userChild)
      }
    }

    return childAns
    
  }

  // 根据儿童ID获取儿童详情
  async getChildDetail(childId: number) {
    const child = await this.childRepo.findOne({ where: { id: childId } })
    
    if (!child) {
      throw new Error('儿童不存在')
    }

    if (child.isDisabled) {
      throw new Error('儿童已被禁用')
    }

    return child
  }

  // 根据儿童ID编辑儿童信息
  async updateChild(childId: number, data: {
    name?: string
    phone?: string
    homeAddress?: string
    birthday?: string
    headImg?: string
    guardian?: string
    gender?: number
  }) {
    const child = await this.childRepo.findOne({ where: { id: childId } })
    
    if (!child) {
      throw new Error('儿童不存在')
    }

    if (child.isDisabled) {
      throw new Error('儿童已被禁用，无法编辑')
    }

    // 验证字段
    if (data.name !== undefined) {
      if (!data.name || data.name.trim().length === 0) {
        throw new Error('姓名不能为空')
      }
      if (data.name.length > 255) {
        throw new Error('姓名长度不能超过255个字符')
      }
    }

    if (data.phone !== undefined) {
      if (!data.phone || data.phone.trim().length === 0) {
        throw new Error('电话不能为空')
      }
      if (data.phone.length > 20) {
        throw new Error('电话长度不能超过20个字符')
      }
    }

    if (data.homeAddress !== undefined && data.homeAddress.length > 255) {
      throw new Error('家庭地址长度不能超过255个字符')
    }

    if (data.birthday !== undefined) {
      const dateRegex = /^\d{4}-\d{2}-\d{2}$/
      if (!dateRegex.test(data.birthday)) {
        throw new Error('生日格式不正确，应为YYYY-MM-DD')
      }
    }

    if (data.headImg !== undefined && data.headImg.length > 255) {
      throw new Error('头像URL长度不能超过255个字符')
    }

    if (data.guardian !== undefined && data.guardian.length > 255) {
      throw new Error('监护人长度不能超过255个字符')
    }

    if (data.gender !== undefined) {
      if (data.gender !== 1 && data.gender !== 2) {
        throw new Error('性别值必须为1（男）或2（女）')
      }
    }

    // 更新字段
    Object.assign(child, data)
    
    return await this.childRepo.save(child)
  }
}